package com.cloud.api.filter;

import com.cloud.base.bean.CloudRequest;
import com.cloud.base.cache.CloudRedisTemplate;
import com.cloud.base.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

import static com.cloud.base.CacheConstant.LOGIN_EXPIRATION_DATE;
import static org.springframework.http.HttpStatus.TOO_MANY_REQUESTS;

//@Component
public class ResponseStatusFilter implements GlobalFilter, Ordered {

    @Autowired
    private CloudRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange).doFinally(a -> {
            ServerHttpResponse response = exchange.getResponse();
            if (response.getStatusCode().equals(TOO_MANY_REQUESTS)) {
                ServerHttpRequest request = exchange.getRequest();
                String token = request.getHeaders().getFirst("token");

                if (StringUtils.isNotBlank(token)) {
                    CloudRequest cloudRequest = redisTemplate.get(token);
                    if (cloudRequest != null) {
                        String key = LOGIN_EXPIRATION_DATE.concat(cloudRequest.getUserId());
                        String expir = redisTemplate.get(key);
                        expir = expir == null ? "0" : expir;
                        Long expirCount = Long.valueOf(expir);

                        if (expirCount < 10) {
                            Date now = DateUtil.addDate(new Date(), 1);
                            expirCount = expirCount + 1;
                            String count = String.valueOf(expirCount == 10 ? now.getTime() : expirCount);
                            redisTemplate.set(key, count, 86400);
                        }
                    }
                }
            }
        });
    }

    public int getOrder() {
        return -3;
    }
}